<div class="list">
    <form class="layui-form" id="test" style="display:none" >
        <div class="layui-form-item">
            <label class="layui-form-label">名称</label>
            <div class="layui-input-block">
                <input type="text" name="name" required  lay-verify="required" placeholder="请输入名称" autocomplete="on" class="layui-input" id="name" style="width: 300px;">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">图层</label>
            <div class="layui-input-block">
                <input type="text" name="background" required  lay-verify="required" placeholder="请选择平面图" autocomplete="on" class="layui-input" id="background" style="width: 300px;" hidden="">
                <input id="pic" onChange="background.value=this.value" type="file" accept=".bmp,.jpg,.png,.jpeg,image/bmp,image/jpg,image/png,image/jpeg"></input>
            </div>
        </div>
    </form>

    <form class="layui-form" id="jiankong" style="display:none" >
        <div class="layui-form-item">
            <label class="layui-form-label">单选框</label>
            <div class="layui-input-block">
                <input type="radio" lay-filter="type" name="type" value="1" title="图标" checked="">
                <input type="radio" lay-filter="type" name="type" value="2" title="文本">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">名称</label>
            <div class="layui-input-block">
                <input type="text" name="name" required  lay-verify="required" placeholder="请输入名称" autocomplete="on" class="layui-input" id="pointName" style="width: 300px;">
            </div>
        </div>
        <div id="flex" style="display: none;">
            <div class="layui-form-item">
                <label class="layui-form-label">数值</label>
                <div class="layui-input-block">
                    <input type="text" name="value" required placeholder="请输入数值" autocomplete="on" class="layui-input" id="pointValue" style="width: 300px;">
                </div>
            </div>
        </div>
        <div id="linkage">
            <div class="layui-form-item">
                <label class="layui-form-label">云盒</label>
                <div class="layui-input-block" id="xiala">
                    <select name="box" id="box" lay-filter="box">
                        <option value="0">请选择云盒</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">柜子</label>
                <div class="layui-input-block" id="xiala">
                    <select name="cabinet" id="cabinet" lay-filter="cabinet">
                        <option value="0">请选择柜子</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">详情</label>
                <div class="layui-input-block" id="xiala">
                    <select name="detail" id="detail" lay-filter="detail">
                        <option value="0">请选择详情</option>
                    </select>
                </div>
            </div>
        </div>
    </form>

    <div class='l-container'>
        <div class="c-left">
            @if($background)
            <div id="canvas">
                <img id="picture" src="{{ $background }}" />
            </div>
            @else
            <div>
                <img id="picture" src="" />
                <img id="upload" src="/project-layer/image/upload.png"/>
            </div>
            @endif
        </div>
        <div class="c-right">
          <div class="right-header">
            <input type="button" value="添加点位" class="btn" id="btn_add" />
            <input type="button" value="添加图层" class="btn" id="btn_layer" />
            <input type="button" value="保存" class="btn" id="btn_save" />
          </div>
          <div class="right-main">
              <div id="menuTree" class="demo-tree demo-tree-box"></div>
          </div>
        </div>
    </div>
</div>
<script type="text/javascript">
Dcat.ready(function () {
    var icon = "{{ asset('/project-layer/image/normal.png') }}";
    //初始化计数器
    var num = 0;
    //区块锁定标识
    var lock = false;
    //加载layer拓展
    layer.config({
        extend: 'extend/layer.ext.js'
    });
    //右键菜单参数
    context.init({
        fadeSpeed: 100,
        filter: function ($obj){},
        above: 'auto',
        preventDoubleContext: true,
        compress: false
    });
    //调试输出方法
    function debug(msg){
        $("#debug").text(msg);
    }
    function createBox(data){
        var dataId = data.id || '';
        var type = data.type || 1;
        var value = data.value || 0;
        var height = data.height || 30;
        var width = data.width || 30;
        var pageX = data.pageX || 0;
        var pageY = data.pageY || 0;
        var name = data.name || '';
        var alias = data.alias || '';
        //更新计数器并记录当前计数
        var curNum = num++;
        //创建区域块
        console.log(data);
        var pos = $("#canvas").position();
        var color = "rgb(255, 0, 0)";
        if (type == 1) {
            var box = $('<div class="box" type="'+type+'" rel="'+curNum+'" dataId="'+dataId+'" alias="'+alias+'" name="'+name+'"><div class="center"><img style="height20px;width:20px;" id="' + alias + '" src="' + icon + '" /><p style="width:100px;">' + name + '<\/p><\/div><\/div>').css({
                width : width,
                height : height,
                top : pageY > 0 ? pageY : (pos.top > 0 ? 0 : pos.top * -1 + 50),
                left : pageX > 0 ? pageX : (pos.left > 0 ? 0 : pos.left * -1 + 30)
            }).appendTo("#canvas");
        } else {
            var box = $('<div class="box" rel="'+curNum+'" dataId="'+dataId+'" name="'+name+'" alias="'+alias+'" value="'+value+'" type="'+type+'"><pre class="content"><div>'+name+'</div><div>'+value+'</div></pre></div>').css({
                width : 120,
                height : 50,
                top : pageY > 0 ? pageY : (pos.top > 0 ? 0 : pos.top * -1 + 50),
                left : pageX > 0 ? pageX : (pos.left > 0 ? 0 : pos.left * -1 + 30)
            }).appendTo("#canvas");
        }

        context.attach('.box[rel='+curNum+']', [
            {header: '操作'},
            {text: '删除区域', action: function(e){
                    e.preventDefault();
                    $('.box[rel='+curNum+']').remove();
                }
            },
        ]);
    }

    layui.use('form', function(){
      var form = layui.form;
      form.on('radio(type)', function(data){
        if (data.value == 2) {
            $("#flex").show();

        } else if (data.value == 1) {
            $("#flex").hide();
            $("#pointValue").val('');
        }
      });

      form.on('select(box)', function(data){
        $("#cabinet").val(0);
        $("#detail").val(0);
        $.ajax({
            type: "GET",//规定传输方式
            url: "{{ URL::asset('admin/project-layer/getCabinets') }}",//提交URL
            data:{
                boxId:data.value,
            },
            success: function(data){
                $.each(data,function(index,value){
                    $("#cabinet").append(new Option(value.text,value.id));
                });
                form.render("select");
            }
        });
      });

      form.on('select(cabinet)', function(data){
        $("#detail").val(0);
        $.ajax({
            type: "GET",//规定传输方式
            url: "{{ URL::asset('admin/project-layer/getDetail') }}",//提交URL
            data:{
                cabinetId:data.value,
                type:$("input[name='type']:checked").val(),
            },
            success: function(data){
                $.each(data,function(index,value){
                    $("#detail").append(new Option(value.text,value.alias));
                });
                form.render("select");
            }
        });
      });

    });

    //获取下拉设备类型
    layui.use('form',function(){
        var form= layui.form;
        $.ajax({
            type: "GET",//规定传输方式
            url: "{{ URL::asset('admin/project-layer/getBoxes') }}",//提交URL
            success: function(data){
                $.each(data,function(index,value){
                    $("#box").append(new Option(value.text,value.id));
                });
                form.render("select");
            }
        });
    });
    //添加监控点
    $("#btn_add").click(function(){
        layer.open({
            type:1,
            area:['500px','500px'],
            title: '新增点位'
            ,content: $("#jiankong"),
            shade: 0,
            btn: ['提交', '关闭']
            ,btn1: function(index, layero){
                var type=$("input[name='type']:checked").val();
                var pointName = $("#pointName").val();
                if(pointName==''){
                    layer.msg('请填写名称');
                    return false
                }
                var box=$("#box").val();
                var cabinet=$("#cabinet").val();
                var detail=$("#detail").val();
                var value=$("#pointValue").val();
                
                let url = "/admin/project-layer/add-point";
                let data1 = {
                    type:type,
                    pointName:pointName,
                    pointValue:value,
                    box:box,
                    cabinet:cabinet,
                    detail: detail,
                    projectId:'{{ $projectId }}',
                    layerId:'{{ $layerId }}',
                    _token:'{{ csrf_token() }}',
                }
                $.ajax({
                type: "POST",//规定传输方式
                url: url,//提交URL
                data: data1,//提交的数据
                    success: function(res){
                        if(res.code == 1){
                            var dot = {
                                id: res.data.id,
                                type: res.data.type,
                                value: res.data.value,
                                name: res.data.name,
                                alias: res.data.point_alias,
                            }
                            createBox(dot);
                            layer.closeAll();
                        }
                        layer.msg(res.msg);
                        return;
                    }
                });
            },
            btn2: function(index, layero){
                layer.closeAll();
                // return false;
            },
            cancel: function(layero,index){ 
                layer.closeAll();
            }
        }); 
    });

    function addLayer(index, layero){
        var name = $("#name").val();
        var background=$("#pic")[0].files[0];
        if(name==''||background==''){
            layer.msg('必须都填满才能提交');return false
        }
        let url = "/admin/project-layer/add-layer";
        formdata = new FormData();
        formdata.append('background',background);
        formdata.append('projectId', '{{ $projectId }}');
        formdata.append('_token','{{ csrf_token() }}');
        formdata.append('name',name);

        $.ajax({
            type: "POST",//规定传输方式
            url: url,//提交URL
            data: formdata,//提交的数据
            contentType:false,
            processData : false, 
            success: function(res){
                if(res.code == 1){
                    // var picurl = res.data.image;
                    // imgs = document.getElementById("picture");
                    // imgs.setAttribute("src",picurl);
                    // document.getElementById("upload").setAttribute("style",'display:none;');
                    layer.closeAll();
                    layer.msg(res.msg);
                    
                    setTimeout(() => {
                        window.location.replace(res.data.url)
                    }, 3000);

                } else {
                    layer.msg(res.msg);
                }
            }
        });
    }

    //无楼添加图层
    $("#upload").click(function(){
        layer.open({
            type:1,
            area:['500px','400px'],
            title: '上传图层'
            ,content: $("#test"),
            shade: 0,
            btn: ['提交', '关闭']
            ,btn1: function(index, layero){
                addLayer(index, layero);
            },
            btn2: function(index, layero){
                layer.closeAll();
            },
            cancel: function(layero,index){ 
                layer.closeAll();
            }
        });
    });

    //添加图层
    $("#btn_layer").click(function(){
        layer.open({
            type:1,
            area:['500px','400px'],
            title: '上传图层'
            ,content: $("#test"),
            shade: 0,
            btn: ['提交', '关闭']
            ,btn1: function(index, layero){
                addLayer(index, layero);
            },
            btn2: function(index, layero){
                layer.closeAll();
            },
            cancel: function(layero,index){ 
                layer.closeAll();
            }
        });
    });

    //保存
    $('#btn_save').click(function(){
        var data = [];
        //获取实际屏幕显示区域尺寸
        var dom = document.getElementById("picture");
        var Ratio = 1600/dom.offsetWidth;
        $('.box').each(function(){
            var box = {};
            box['id'] = $(this).attr('dataId');
            box['type'] = $(this).attr('type');
            box['value'] = $(this).attr('value');
            box['name'] = $(this).attr('name');
            box['alias'] = $(this).attr('alias');
            box['height'] = $(this).height();
            box['width'] = $(this).width();
            box['pageX'] = $(this).position().left;
            box['pageY'] = $(this).position().top;
            data.push(box);
        });
        let url = "/admin/project-layer/save-coordinate";
        let postData = {
            layerId:'{{ $layerId }}',
            _token: '{{ csrf_token() }}',
            data: data
        }
        $.ajax({
           type: "POST",//规定传输方式
           url: url,//提交URL
           data: postData,//提交的数据
           success: function(res){
                layer.msg(res.msg);
           }
        });
    });
    //创建拖拽方法
    $("#canvas").mousedown(function(e){
        var canvas = $(this);
        e.preventDefault();
        var pos = $(this).position();
        this.posix = {'x': e.pageX - pos.left, 'y': e.pageY - pos.top};
        $.extend(document, {'move': true, 'move_target': this, 'call_down' : function(e, posix){
            canvas.css({
                'cursor': 'move',
                'top': e.pageY - posix.y,
                'left': e.pageX - posix.x
            });
        }, 'call_up' : function(){
            canvas.css('cursor', 'default');
        }});
    }).on('mousedown', '.box', function(e) {
        if(lock) return;
        var pos = $(this).position();
        this.posix = {'x': e.pageX - pos.left, 'y': e.pageY - pos.top};
        $.extend(document, {'move': true, 'move_target': this});
        e.stopPropagation();
    }).on('mousedown', '.box .coor', function(e) {
        var $box = $(this).parent();
        var posix = {
                'w': $box.width(), 
                'h': $box.height(), 
                'x': e.pageX, 
                'y': e.pageY
            };
        $.extend(document, {'move': true, 'call_down': function(e) {
            $box.css({
                'width': Math.max(30, e.pageX - posix.x + posix.w),
                'height': Math.max(30, e.pageY - posix.y + posix.h)
            });
        }});
        e.stopPropagation();
    });

    //数据加载
    @foreach($points as $point)
        createBox(
            {
                id: {{ $point['id'] }},
                type: {{ $point['type'] }},
                value: {{ isset($point['value']) ? $point['value'] : 0}},
                name: "{{ $point['name'] }}",
                alias: "{{ $point['alias'] }}",
                @if(isset($point['pageX']))
                    pageX: {{ $point['pageX'] }},
                @endif
                @if(isset($point['pageY']))
                    pageY: {{ $point['pageY'] }},
                @endif
            }
        );
    @endforeach

    //树状图
    layui.use(['tree', 'util'], function(){
        var tree = layui.tree,
            layer = layui.layer,
            util = layui.util,
            data1 = {!! $tree !!}
      //常规用法
      tree.render({
        elem: '#menuTree' //默认是点击节点可进行收缩
        ,data: data1
        ,isJump: true
        ,showLine: false
        ,click: function(obj){
            console.log(obj.data)
            let url = obj.data.url;
            window.location.href=url
            // console.log(obj.data); //得到当前点击的节点数据
            // console.log(obj.state); //得到当前节点的展开状态：open、close、normal
            // console.log(obj.elem); //得到当前节点元素
            // console.log(obj.data.children); //当前节点下是否有子节点
          }
      });
    });
});
</script>